﻿// See https://aka.ms/new-console-template for more information
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;

var url = "ws://192.168.66.76:15555/ws/audio-dcschat-test?sn=863492053403973";
using (var clientWebSocket = new ClientWebSocket())
{
    var cancellationToken = CancellationToken.None;
    // 连接到服务器
    await clientWebSocket.ConnectAsync(new Uri(url), cancellationToken);
    Console.WriteLine("Connected to server");

    //发送初始化内容
    var initMessage = JsonSerializer.Serialize(new
    {
        type = "init",
        data = new
        {
            userid = "1111",
            sn = "863492053403973"
        }
    });
    await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(initMessage)), WebSocketMessageType.Text, true, cancellationToken);
    Console.WriteLine("init message sent to server");
    Thread.Sleep(1000);
    //发送开始信息
    var startMessage = JsonSerializer.Serialize(new
    {
        type = "start",
        data = new { format = "pcm", sample = 16000, sn = "863492053403973" }
    });
    await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(startMessage)), WebSocketMessageType.Text, true, cancellationToken);
    Thread.Sleep(1000);
    Console.WriteLine("start message sent to server");

    using (var fileStream = new FileStream(ConstConfig.VoicePath, FileMode.Open, FileAccess.Read))
    {
        byte[] buffers = new byte[ConstConfig.bufferSize];
        int bytesRead = 0;
        // 使用while循环读取文件，直到文件结束
        while ((bytesRead = fileStream.Read(buffers, 0, ConstConfig.bufferSize)) > 0)
        {
            ArraySegment<byte> buffer = new ArraySegment<byte>(buffers);
            await clientWebSocket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None);
            Console.WriteLine("file buffer message sent to server");
        }
    }
    //发送开始信息
    var finishMessage = JsonSerializer.Serialize(new
    {
        type = "finish"
    });
    await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(finishMessage)), WebSocketMessageType.Text, true, cancellationToken);
    Console.WriteLine("finish message sent to server");
    var webSocket = new WebSocketExample(clientWebSocket);
    await webSocket.StartAsync();
    ////发送结束信息
    //var endMessage = JsonSerializer.Serialize(new
    //{
    //    type = "finish"
    //});
    //await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(endMessage)), WebSocketMessageType.Text, true, cancellationToken);

}
Console.Read();

public class ConstConfig
{
    public static string VoicePath = "E:\\projects\\语音识别\\我要听歌.pcm";

    public static int bufferSize = 5 * 1024; // 设置缓冲区大小为5k


}
public class WebSocketExample
{
    private readonly WebSocket _webSocket;

    public WebSocketExample(WebSocket webSocket)
    {
        _webSocket = webSocket;
    }

    public async Task StartAsync()
    {
        var receivingTask = Task.Run(async () => await ReceiveMessagesAsync());
        var sendingTask = Task.Run(async () => await SendMessagesAsync());

        await Task.WhenAll(receivingTask, sendingTask);
    }

    private async Task ReceiveMessagesAsync()
    {
        while (_webSocket.State == WebSocketState.Open)
        {
            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
            WebSocketReceiveResult result = await _webSocket.ReceiveAsync(buffer, CancellationToken.None);
            if (result.MessageType == WebSocketMessageType.Close)
            {
                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                var message = System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                Console.WriteLine("Received message: " + message);
            }
        }
    }

    private async Task SendMessagesAsync()
    {
        // Wait for user input and send messages.
        while (_webSocket.State == WebSocketState.Open)
        {
            if (DateTime.Now.Second % 10 == 1)
            {
                var startMessage = JsonSerializer.Serialize(new
                {
                    type = "start",
                    data = new { format = "pcm", sample = 16000, sn = "111" }
                });
                await _webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(startMessage)), WebSocketMessageType.Text, true, CancellationToken.None);
                Console.WriteLine("start message sent to server");
                using (var fileStream = new FileStream(ConstConfig.VoicePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffers = new byte[ConstConfig.bufferSize];
                    int bytesRead = 0;
                    // 使用while循环读取文件，直到文件结束
                    while ((bytesRead = fileStream.Read(buffers, 0, ConstConfig.bufferSize)) > 0)
                    {
                        ArraySegment<byte> buffer = new ArraySegment<byte>(buffers);
                        await _webSocket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None);
                        Console.WriteLine("file buffer message sent to server");
                    }
                }

                var finishMessage = JsonSerializer.Serialize(new
                {
                    type = "finish"
                });
                await _webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(finishMessage)), WebSocketMessageType.Text, true, CancellationToken.None);
                Console.WriteLine("finish message sent to server");
            }
            else
            {
                //Console.WriteLine("等待发送数据");
            }
            System.Threading.Thread.Sleep(1000);
        }
    }
}